package com.jiangjiang.eshop.commodity.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangjiang.eshop.commodity.constant.ApproveResult;
import com.jiangjiang.eshop.commodity.constant.GoodsStatus;
import com.jiangjiang.eshop.commodity.convert.GoodsConvert;
import com.jiangjiang.eshop.commodity.dao.GoodsMapper;
import com.jiangjiang.eshop.commodity.domain.GoodsEntity;
import com.jiangjiang.eshop.commodity.dto.GoodsDTO;
import com.jiangjiang.eshop.commodity.dto.GoodsDetailDTO;
import com.jiangjiang.eshop.commodity.dto.GoodsQueryPageDTO;
import com.jiangjiang.eshop.commodity.dto.GoodsSkuDTO;
import com.jiangjiang.eshop.commodity.state.GoodsStateManager;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsService
 * @Description TODO
 * @Author jhw
 * @Date 2021/7/9 15:36
 * @Version 1.0
 **/
@Service
public class GoodsService extends ServiceImpl<GoodsMapper, GoodsEntity> {

    @Autowired
    private GoodsConvert goodsConvert;
    @Autowired
    private GoodsPictureService goodsPictureService;
    @Autowired
    private GoodsDetailService goodsDetailService;
    @Autowired
    private GoodsDetailPictureService goodsDetailPictureService;
    @Autowired
    private GoodsPropertyValueService goodsPropertyValueService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private GoodsSkuSalePropertyValueService goodsSkuSalePropertyValueService;
    @Autowired
    private GoodsStateManager goodsStateManager;


    /**
     * 统计当前关联类目的商品数量
     *
     * @param categoryId
     * @return
     */
    public Integer countByCategoryId(Long categoryId) {
        LambdaQueryWrapper<GoodsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GoodsEntity::getCategoryId, categoryId);
        return this.count(wrapper);
    }

    /**
     * 更新商品状态
     *
     * @param goodsId 商品id
     * @param status 需要变更的状态
     */
    public void updateGoodsStatus(Long goodsId, Integer status) {
        LambdaUpdateWrapper<GoodsEntity> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(GoodsEntity::getId, goodsId)
                .set(GoodsEntity::getStatus, status);
        this.update(wrapper);
    }

    /**
     * 商品分页查询
     *
     * @param dto 查询条件
     * @return 查询结果
     */
    public Page<GoodsDTO> queryForPage(GoodsQueryPageDTO dto) {
        Page<GoodsEntity> page = new Page<>(dto.getPageNo(), dto.getPageSize(), true);
        LambdaQueryWrapper<GoodsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(dto.getCategoryId() != null, GoodsEntity::getCategoryId, dto.getCategoryId())
                .eq(dto.getBrandId() != null, GoodsEntity::getBrandId, dto.getBrandId())
                .eq(Strings.isNotEmpty(dto.getCode()), GoodsEntity::getCode, dto.getCode())
                .eq(dto.getStatus() != null, GoodsEntity::getStatus, dto.getStatus())
                .like(Strings.isNotEmpty(dto.getName()), GoodsEntity::getName, dto.getName())
                .like(Strings.isEmpty(dto.getSubName()), GoodsEntity::getSubName, dto.getSubName());

        return goodsConvert.convertPage2DTO(this.getBaseMapper().selectPage(page, wrapper));

    }

    /**
     * 根据id查询商品数据
     *
     * @param id 商品id
     * @return 查询结果
     */
    public GoodsDTO queryById(Long id) {
        return goodsConvert.convertEntity2DTO(this.getById(id));
    }

    /**
     * 保存商品数据
     *
     * @param dto 商品数据
     * @return 处理结果
     */
    public Boolean saveGoods(GoodsDTO dto) {
        Boolean result = this.save(goodsConvert.convertDTO2Entity(dto));
        if (result) {
            // 状态变更
            goodsStateManager.create(dto);
        }

        return result;
    }

    /**
     * 更新商品数据
     *
     * @param dto 商品数据
     * @return 处理结果
     */
    public Boolean updateGoods(GoodsDTO dto) {
        if (!goodsStateManager.canEdit(dto)) {
            return false;
        }
        this.updateById(goodsConvert.convertDTO2Entity(dto));
        goodsStateManager.edit(dto);
        return true;
    }

    /**
     * 商品审核
     *
     * @param goodsIs       商品id
     * @param approveResult 审核结果参数
     * @return 处理结果
     */
    public Boolean approve(Long goodsId, Integer approveResult) throws Exception {
        GoodsDTO goodsDTO = this.queryById(goodsId);
        if (!goodsStateManager.canApprove(goodsDTO)) {
            return false;
        }

        goodsStateManager.approve(goodsDTO, approveResult);
        return true;
    }

    /**
     * 执行商品上架操作
     *
     * @param goodsId 商品id
     * @return 处理结果
     */
    public Boolean putOnShelves(Long goodsId) {
        GoodsDTO goodsDTO = this.queryById(goodsId);
        if (!goodsStateManager.canPutOnShelves(goodsDTO)) {
            return false;
        }
        goodsStateManager.putOnShelves(goodsDTO);
        return true;
    }

    /**
     * 执行商品下架操作
     *
     * @param goodsId 商品id
     * @return 处理结果
     */
    public Boolean putOffShelves(Long goodsId) {
        GoodsDTO goodsDTO = this.queryById(goodsId);
        if (!goodsStateManager.canPullOffShelves(goodsDTO)) {
            return false;
        }
        goodsStateManager.pullOffShelves(goodsDTO);
        return true;
    }


    /**
     * 执行删除操作
     *
     * @param goodsId 商品id
     * @return 操作结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeGoods(Long goodsId) {
        GoodsDTO goodsDTO = this.queryById(goodsId);
        if (!goodsStateManager.canRemove(goodsDTO)) {
            return false;
        }

        // 删除关联的商品图片
        goodsPictureService.removeByGoodsId(goodsId);

        GoodsDetailDTO detail = goodsDetailService.queryByGoodsId(goodsId);
        // 删除明细关联的图片数据
        goodsDetailPictureService.removeByDetailId(detail.getId());
        // 删除关联的明细数据
        goodsDetailService.removeById(detail.getId());
        // 删除关联的数据值数据
        goodsPropertyValueService.removeByGoodsId(goodsId);
        List<Long> skuIds = goodsSkuService.queryByGoodsId(goodsId).stream()
                .map(GoodsSkuDTO::getId)
                .collect(Collectors.toList());
        // 删除关联的sku数据
        goodsSkuService.removeByIds(skuIds);
        // 删除sku关联的销售属性数据
        goodsSkuSalePropertyValueService.batchRemoveBySkuIds(skuIds);

        // 删除商品数据
        return this.removeById(goodsId);
    }

}
